package cn.innosmart.aq.view.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import cn.innosmart.aq.R;
import cn.innosmart.aq.util.EditTextCheckUtil;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;

/**
 * Created by David on 2015/7/16.
 */
public class CountFindPasswordFragment extends BaseFragment implements INetworkInteractUtil {
    private static final int CHANGE_LOADINGDOT_WHAT = 100001;
    private final int ERROR = 2;
    private final int PASSWORDNONE = -11;
    private final int PASSWORDNUMLESS = -12;
    private final int RESETSUCCESS=0;
    private View view;
    private EditText etPassword;
    private Button btNext;
    private EditText etVerify;
    private String code;
    private NetworkInteractUtil networkInteractUtil;
    private String userName;
    private int verification_code;
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bt_next:
                    String password = etPassword.getText().toString().trim();
                    int ret = EditTextCheckUtil.checkPassword(password);
                    String verifyCodeStr = etVerify.getText().toString();
                    if (ret == PASSWORDNONE) {
                        showToast(getString(R.string.password_can_not_empty));
                        return;
                    } else if (ret == PASSWORDNUMLESS) {
                        showToast(getString(R.string.password_length_can_not_below_six));
                        return;
                    }
                    if (TextUtils.isEmpty(verifyCodeStr)) {
                        showToast(getString(R.string.verifycode_can_not_empty));
                        return;
                    } else {
                        try {
                            int verifyCode = Integer.valueOf(verifyCodeStr);
                            if (verifyCode != verification_code) {
                                showToast(getString(R.string.verifycode_wrong));
                                return;
                            }
                        } catch (Exception e) {
                            showToast(getString(R.string.verifycode_wrong));
                            return;
                        }
                    }
                    networkInteractUtil.resetPassword(userName, password, verifyCodeStr);
                    break;
                case R.id.bt_resend:
                    if (userName != null)
                        networkInteractUtil.findPasswordVerify(userName);
                    else
                        showToast(getString(R.string.username_can_not_empty));
                    break;
            }
        }
    };
    private int countdown = 60;
    private Button btResend;
    /**
     * 设置Toolbar
     */
    private Toolbar toolbar;
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getActivity().onBackPressed();
        }
    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESETSUCCESS:
                    swichCountLoginFragment();
                    break;
                case ERROR:
                    String message = (String) msg.obj;
                    showToast(message);
                    break;
                case CHANGE_LOADINGDOT_WHAT:
                    countdown--;
                    if (countdown > 0) {
                        mHandler.sendEmptyMessageDelayed(CHANGE_LOADINGDOT_WHAT, 1000);
                        btResend.setText(String.valueOf(countdown) + "s");
                    } else {
                        btResend.setText(R.string.send_verifycode);
                        btResend.setEnabled(true);
                    }
                    break;
            }
        }
    };

    private void assignViews(View view) {
        etPassword = (EditText) view.findViewById(R.id.et_newpwd);
        etVerify = (EditText) view.findViewById(R.id.et_verify);
        btNext = (Button) view.findViewById(R.id.bt_next);
        btResend = (Button) view.findViewById(R.id.bt_resend);
        btResend.setEnabled(false);
        btResend.setOnClickListener(mOnClickListener);
        mHandler.sendEmptyMessage(CHANGE_LOADINGDOT_WHAT);
    }

    private void setListener() {
        btNext.setOnClickListener(mOnClickListener);
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getCountdown() {
        return countdown;
    }

    public void setCountdown(int countdown) {
        this.countdown = countdown;
    }

    public int getVerification_code() {
        return verification_code;
    }

    public void setVerification_code(int verification_code) {
        this.verification_code = verification_code;
    }

    /**
     * 切换到找回密码页面
     */
    private void switchToFindPasswordFragment() {
        CountFindPasswordFragment fragment = new CountFindPasswordFragment();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx.replace(R.id.ll_content, fragment, "findpd");
        tx.addToBackStack(null);
        tx.commit();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_findpassword, container, false);
        setBar();
        networkInteractUtil = new NetworkInteractUtil(this);
        assignViews(view);
        setListener();
        return view;
    }

    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        ((ImageView) getActivity().findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView)  getActivity().findViewById(R.id.tv_toolbar)).setText(getString(R.string.title_findpd));
//        toolbar.setNavigationOnClickListener(onNavigationClickListener);
        getActivity().findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
    }

    public void swichCountLoginFragment() {
        CountLoginFragment fragment;
        FragmentManager fm = getFragmentManager();
        fragment = (CountLoginFragment) fm.findFragmentByTag("countlogin");
        if (fragment == null) {
            fragment = new CountLoginFragment();
        }
        FragmentTransaction tx = fm.beginTransaction();
        tx.replace(R.id.ll_content, fragment, "countlogin");
        tx.commit();
    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
        if (flag.equals(networkInteractUtil.RESETPASSWORD)) {
            switch (ret) {
                case 0:
                    mHandler.sendEmptyMessage(RESETSUCCESS);
                    break;
                default:
                    Message msg = mHandler.obtainMessage();
                    msg.what = ERROR;
                    msg.obj = object;
                    mHandler.sendMessage(msg);
                    break;
            }
        }else if (flag.equals(networkInteractUtil.FINDPASSWORDVERIFY)) {
            switch (ret) {
                case 0:
                    try {
                        JSONObject jsonResult = new JSONObject((String) object);
                        verification_code = jsonResult.getInt("verification_code");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    Message msg = mHandler.obtainMessage();
                    msg.what = ERROR;
                    msg.obj = object;
                    mHandler.sendMessage(msg);
                    break;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }
}
